/**
 * 
 */
package com.moyq5.permit.center.web.controller;

import java.util.Collection;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.moyq5.permit.center.bean.entity.Agent;
import com.moyq5.permit.center.bean.entity.Merch;
import com.moyq5.permit.center.bean.entity.Shop;
import com.moyq5.permit.center.bean.entity.SysAdmin;
import com.moyq5.permit.center.feign.client.AgentFeign;
import com.moyq5.permit.center.feign.client.MerchFeign;
import com.moyq5.permit.center.feign.client.ShopFeign;
import com.moyq5.permit.center.feign.client.SysAdminFeign;

/**
 * @author Moyq5
 * @date 2019年7月29日
 */
public class AbstractLoginController extends AbstractExceptionController {

	@Autowired
	protected SysAdminFeign adminFeign;
	@Autowired
	protected AgentFeign agentFeign;
	@Autowired
	protected MerchFeign merchFeign;
	@Autowired
	protected ShopFeign shopFeign;

	protected Long getLoginAdminId() {
		return getLoginId("permit-center");
	}

	protected SysAdmin getLoginAdmin() {
		return adminFeign.one(getLoginAdminId()).getData();
	}

	protected Long getLoginAgentId() {
		return getLoginId("agent-center");
	}

	protected Agent getLoginAgent() {
		Long agentId = getLoginAgentId();
		if (null == agentId) {
			//agentId = 2L;//调试
			return null;
		}
		return agentFeign.one(agentId).getData();
	}

	protected Long getLoginMerchId() {
		return getLoginId("merch-center");
	}

	protected Merch getLoginMerch() {
		Long merchId = getLoginMerchId();
		if (null == merchId) {
			//merchId = 2L;//调试
			return null;
		}
		return merchFeign.one(merchId).getData();
	}

	protected Long getLoginShopId() {
		return getLoginId("shop-center");
	}

	protected Shop getLoginShop() {
		Long shopId = getLoginShopId();
		if (null == shopId) {
			//shopId = 4L;//调试
			return null;
		}
		return shopFeign.one(shopId).getData();
	}

	private Long getLoginId(String realm) {
		Subject subject = SecurityUtils.getSubject();
		PrincipalCollection pc = subject.getPrincipals();
		Collection<?> coll = pc.fromRealm(realm);
		if (null == coll || coll.size() == 0) {
			return null;
		}
		return (Long) coll.iterator().next();
	}

}
